<?php

//UMA new
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\ContactStoreRequest;
use App\Models\ContactInfo;
use App\Events\ContactInfoSaved;
use App\Traits\TestLog;
use Auth;
use App\Models\customerHistory;
use GuzzleHttp\Exception\RequestException;

class ContactController extends BaseController
{
    use TestLog;
        
    /**
     * 保存咨询信息
     * 相談情報を保存する
     * @param  mixed $request
     * @return json response
     */
    public function store(ContactStoreRequest $request)
    {
        $user = Auth::user();
        $customerHistory = $user->histories()->findOrFail($request->input('customer_history_id'));

        
        $datas = $request->input();
        $datas['temporary_member_id'] = Auth::user()->temporary_member_id;
        try {
            $contact = $customerHistory->contact()->create($datas);
        } catch (\Exception $e) {
            $this->loginfo([$e->getMessage()], 'failed to create a contact:');
            return response()->json(['error' => $e->getMessage()]);
        }

        if ($contact) {
            //保存成功，触发事件
            //正常に保存，トリガーイベント
            try {
                event(new ContactInfoSaved($contact));
                return $this->success([
                    'msg' => '正常に作成されました',
                    'contact_info_id' => $contact->id
                ]);
            } catch (RequestException $e) {
                $response = $e->getResponse();
                $content = json_decode($response->getBody(), true);
                $this->loginfo($content, 'error:');
                return response()->json($content,400);
            }
        }

        return $this->error('400', ['msg' => '追加に失敗しました']);
    }
}
